<script setup>
import {useRoute} from 'vue-router';
import HeaderNav from '@/components/HeaderNav.vue'
import {getHouse, getImagesApi, updateHouse} from '@/api/house/house.js'
import {addContract} from "@/api/contract/contract.js";
import {addMonthsToDate} from "@/utils/data.js";
import {ElMessage} from 'element-plus'
import store from '@/store'
import CommentItem from "@/components/CommentItem.vue";
import {listHouseCollectApi, addHouseCollectApi, cancelHouseCollectApi} from '@/api/house/house-collect.js'
import {addComment, listComment} from "@/api/house/comment.js";

const currentUser = store.state.value.user// 当前登录的用户存储状态
const route = useRoute();// 使用 useRoute 获取路由对象
const houseId = route.params.id;// 从 route.params 中获取动态路由参数
const house = ref({})// 房源信息
const images = ref([])// 房间图片
const number = ref(1)// 租期
const buyerName = ref('') // 买家姓名
const buyerPhone = ref('')  // 买家电话
const dialogVisible = ref(false) // 订单弹窗
const houseCollect = ref({})
const content = ref("")// 评论内容
// 评论列表数据
const comments = ref()


const handleOrder = () => {
  dialogVisible.value = true
}
// 收藏
const handleCollect = () => {
  if (houseCollect.value) {
    cancelHouseCollectApi(houseCollect.value).then(res => {
      ElMessage.success('取消收藏成功.')
    })
    houseCollect.value = null
  } else {
    houseCollect.value = {
      houseId: houseId,
      userId: currentUser.id
    }
    addHouseCollectApi(houseCollect.value).then(res => {
      ElMessage.success('收藏成功.')
    })
  }
}
// 签署合同
const signContract = async () => {
  if (!buyerName.value || !buyerPhone.value) {
    ElMessage.error('买家信息不能为空.')
  } else {
    addContract({
      houseId: houseId,
      buyerName: buyerName.value,
      buyerPhone: buyerPhone.value,
      rentalPeriod: number.value,
      startDate: new Date(),
      endDate: addMonthsToDate(number.value),
      totalAmount: house.value.rent * number.value,
      status: '1',
      buyerId: currentUser.id,
    })
    house.value.status = '1'
    await updateHouse(house.value)
    ElMessage.success('下单成功.')
    dialogVisible.value = false
  }
}

const getComments = () => {
  listComment({houseId: houseId}).then(res => {
    comments.value = res.rows
  })
}
// 发表评论
const makeComment = () => {
  if (!content.value) {
    ElMessage.error('评论内容不能为空.')
  } else {
    const newComment = {
      houseId: houseId,
      userId: currentUser.id,
      userName: currentUser.userName,
      comment: content.value,
    }
    addComment(newComment).then(res => {
      ElMessage.success('评论成功.')
      getComments()
      content.value = ''
    })
  }
}


onMounted(() => {
  getHouse(houseId).then(res => {
    house.value = res.data
  })
  getImagesApi(houseId).then(res => {
    images.value = res.data.split(",")
  })
  listHouseCollectApi({userId: currentUser.id, houseId: houseId}).then(res => {
    houseCollect.value = res.rows.length > 0 ? res.rows[0] : null
  })
  getComments()
})
</script>

<template>
  <div class="box">
    <header-nav :active="-1" style="width: 100vw;"/>
    <div class="container">
      <el-carousel height="480px" type="card">
        <el-carousel-item v-for="item in images" :key="item.id">
          <img :src="`/dev-api/${item}`" alt="" class="image"/>
        </el-carousel-item>
      </el-carousel>
      <div style="display: flex;justify-content: space-between;margin-top: 20px;">
        <div class="info">
          <el-descriptions class="margin-top" title="房屋详细信息" :column="3" size="large" border>
            <el-descriptions-item label="状态">{{ house.status == '0' ? '未售出' : '已售出' }}</el-descriptions-item>
            <el-descriptions-item label="房产证编号">{{ house.propertyCertificateNo }}</el-descriptions-item>
            <el-descriptions-item label="租金">{{ house.rent }}元/月</el-descriptions-item>
            <el-descriptions-item label="卧室数量">{{ house.bedroomCount }}</el-descriptions-item>
            <el-descriptions-item label="卫生间数量">{{ house.bathroomCount }}</el-descriptions-item>
            <el-descriptions-item label="厨房数量">{{ house.kitchenCount }}</el-descriptions-item>
            <el-descriptions-item label="客厅数量">{{ house.livingroomCount }}</el-descriptions-item>
            <el-descriptions-item label="房屋面积">{{ house.area }}平方米</el-descriptions-item>
            <el-descriptions-item label="是否有空调">{{
                house.hasAirConditioner == '0' ? '没有' : '有'
              }}
            </el-descriptions-item>
            <el-descriptions-item label="建成年份">{{ house.buildYear }}</el-descriptions-item>
            <el-descriptions-item label="朝向">{{ house.rent }}</el-descriptions-item>
            <el-descriptions-item label="楼层">{{ house.floor }}</el-descriptions-item>
            <el-descriptions-item label="是否有电梯">{{
                house.hasElevator == '0' ? '没有' : '有'
              }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人">{{ house.contactName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ house.contactPhone }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="order">
          <div class="price">
            {{ house.rent }}元/月
          </div>
          <div class="month">
            <h1>租住月数</h1>
            <el-input-number v-model="number" :disabled="house.status=='1'" :min="1" :max="10" size="large"
                             style="width: 100%;"/>
            <el-button style="width: 100%;margin-top: 20px;" size="large"
                       type="danger" @click="handleCollect"
                       :disabled="house.status=='1'">
              {{ houseCollect ? '取消收藏' : '收藏' }}
            </el-button>
            <el-button type="primary" style="width: 100%;margin-top: 20px;" size="large"
                       @click="handleOrder" :disabled="house.status=='1'">
              立即预约
            </el-button>
          </div>
        </div>
      </div>

      <!-- 评论列表 -->
      <div style="margin-top: 20px;background: #fff;padding: 20px">
        <el-input placeholder="请输入评论内容" v-model="content"
                  style="margin-top: 20px;" type="textarea"/>
        <el-button type="primary" style="margin-top: 20px;" @click="makeComment">发表评论</el-button>
        <CommentItem v-for="item in comments" :key="item.id" :comment="item"/>
      </div>
    </div>

    <!-- 合同弹出框 -->
    <el-dialog v-model="dialogVisible" width="600px" title="购房合同">
      <!-- 合同内容 -->
      <div class="contract-content">
        <p>甲方（房主）：{{ house.contactName }}</p>
        <p style="display: flex;align-items: center">
          <span>乙方（购买人）：</span>
          <el-input placeholder="请输入乙方姓名" style="width: 200px;" v-model="buyerName"></el-input>
        </p>
        <p style="display: flex;align-items: center">
          <span>乙方联系方式：</span>
          <el-input placeholder="请输入乙方联系方式" style="width: 200px;" v-model="buyerPhone"></el-input>
        </p>
        <p>甲乙双方经友好协商，就以下房产的购房事宜达成如下协议：</p>

        <p>1. 房屋位于 {{ house.houseName }}，总面积为 {{ house.area }} 平方米。</p>
        <p>2. 购房款总计为 {{ house.rent * number }} 元，乙方应在合同签订之日起 10 天内支付全款。</p>
        <p>3. 甲方应在乙方付款后 10 天内将房屋交付给乙方。</p>
        <p>4. 本合同一式两份，甲乙双方各执一份，自签字之日起生效。</p>
      </div>

      <!-- 弹窗底部操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="signContract">签署合同</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">

.box {
  background: #f0f4f9;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100vw;
  padding-bottom: 28px;
}

.container {
  width: 70%;
}

.image {
  width: 100%;
  height: 480px;
  object-fit: cover;
}

.info {
  width: 70%;
  margin-right: 30px;
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  font-size: 200px;
}

.order {
  width: 30%;
  background: #fff;
  border-radius: 10px;

  .price {
    width: 100%;
    height: 60px;
    display: flex;
    justify-content: start;
    align-items: center;
    padding-left: 20px;
    color: #fff;
    border-radius: 10px 10px 0 0;
    background: #1ab394;
    font-size: 30px;
    font-weight: bold;
  }
}

.month {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
